import 'package:flutter/material.dart';
import 'package:mall/core/providers/pages/mine/web_view_model.dart';
import 'package:provider/provider.dart';
import 'package:webview_flutter/webview_flutter.dart';

class WebViewPageArgs {
  final String title;
  final String subTitle;
  final String url;
  final bool query;

  WebViewPageArgs(
    this.title,
    this.subTitle,
    this.url, {
    this.query = false,
  });
}

class WebViewPage extends StatelessWidget {
  static const routeName = '/WebViewPage';
  final WebViewPageArgs args;

  WebViewPage({
    Key key,
    @required this.args,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (context) => WebViewModel(),
      child: Scaffold(
        appBar: AppBar(
          title: Text(args.title),
        ),
        body: Column(
          children: <Widget>[
            Container(
              alignment: Alignment.centerLeft,
              padding: EdgeInsets.only(left: 12),
              color: Colors.white,
              height: 50,
              child: Text(args.subTitle),
            ),
            Expanded(
              child: Builder(
                builder: (context) {
                  return WebView(
                    initialUrl: args.url,
                    onPageFinished: (url) {
                      _onPageFinished(context);
                    },
                  );
                },
              ),
            ),
            if (args.query)
              Container(
                margin: EdgeInsets.all(12),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                  children: <Widget>[
                    RaisedButton(
                      onPressed: () {
                        Navigator.of(context).pop(false);
                      },
                      color: Colors.grey,
                      child: Text('不同意'),
                    ),
                    Consumer<WebViewModel>(
                      builder: (context, model, child) {
                        return RaisedButton(
                          onPressed: model.finished
                              ? () {
                                  Navigator.of(context).pop(true);
                                }
                              : null,
                          child: Text('同意${model.count > 0 ? '(${model.count}s)' : ''}'),
                        );
                      },
                    ),
                  ],
                ),
              ),
          ],
        ),
      ),
    );
  }

  void _onPageFinished(BuildContext context) async {
    WebViewModel model = Provider.of(context, listen: false);
    // 添加延时5秒才能点击
    while (model.count > 0) {
      await Future.delayed(Duration(seconds: 1));
      model.count--;
    }
    // 标记完成，可以点击同意了
    model.finished = true;
  }
}
